import java.awt.Dimension;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.JDesktopPane;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.SwingConstants;
import javax.swing.ImageIcon;
import javax.swing.JMenuBar;
import javax.swing.JButton;
import java.awt.Color;
import javax.swing.JTable;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.File;

import javax.swing.JTextField;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;


public class Menu extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private JPanel contentPane;

	private JTable table;
	public static JTable table_1;
	public static DefaultTableModel modelo= new DefaultTableModel();
	public static JLabel lblNewLabel = new JLabel("");
	
	public static ISupermercado Super= new TSupermercado();
	public static CargarMasiva manejadorsuper=new CargarMasiva();
	public ILista listaADevolver = new TLista();


	
	

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					Menu frame = new Menu();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public Menu() {
		setResizable(false);
	
		JDesktopPane esc= new JDesktopPane();
		getContentPane().add(esc);
		setBackground(Color.WHITE);
		setTitle("Hipermecado Geant");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 782, 675);
		
		JMenuBar menuBar = new JMenuBar();
		menuBar.setBackground(new Color(0, 128, 128));
		setJMenuBar(menuBar);
		
		
		JButton btnAgregarProducto = new JButton("Agregar Producto");
		btnAgregarProducto.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				AltasProductos Ap= new AltasProductos();
				Ap.setVisible(true);
			}
		});
		btnAgregarProducto.setBackground(new Color(60, 179, 113));
		btnAgregarProducto.setForeground(new Color(255, 250, 250));
		btnAgregarProducto.setFont(new Font("Arial", Font.BOLD, 14));
		menuBar.add(btnAgregarProducto);
		
		JButton btnEliminarStock = new JButton("Eliminar Producto");
		btnEliminarStock.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				int fila_selected=table_1.getSelectedRow();
				if(fila_selected<0){
					JOptionPane.showMessageDialog(null, "Error: Lista vacia o celda no seleccionada");
				}
				else{
									
					String id=(String)table_1.getValueAt(table_1.getSelectedRow(), 0);							
					Super.eliminarProducto(id);
					modelo.removeRow(fila_selected);
					
				}
			}
		});
		btnEliminarStock.setBackground(new Color(60, 179, 113));
		btnEliminarStock.setForeground(new Color(255, 250, 250));
		btnEliminarStock.setFont(new Font("Arial", Font.BOLD, 14));
		menuBar.add(btnEliminarStock);

		 final JSpinner spinner = new JSpinner();
		 spinner.setModel(new SpinnerNumberModel(new Integer(1), null, null, new Integer(1)));
		 spinner.setFont(new Font("Arial Black", Font.BOLD, 12));
		
		JButton btnReducirProducto = new JButton("Aumentar Stock");
		btnReducirProducto.addActionListener(new ActionListener() {

			
			public void actionPerformed(ActionEvent arg0) {
				
				Object cantidadaumentada=spinner.getValue();
				int cantspin= ((Integer) cantidadaumentada);
				if (cantspin>0){
				
				
				Comparable id=(String)table_1.getValueAt(table_1.getSelectedRow(), 0);	
				String cantstock=(String)Menu.table_1.getValueAt(Menu.table_1.getSelectedRow(), 3);
				
				
				int stck=Integer.valueOf(cantstock.trim()).intValue();
				int cantactual=stck+cantspin;
				
				
				
				if (Menu.Super.agregarStockProducto(id,cantspin)){
					Menu.table_1.setValueAt(cantactual,Menu.table_1.getSelectedRow(),3);
					
					
					
					
					JOptionPane.showMessageDialog(null, "Se aumento el stock");
				}
				}
				
					
				else
					JOptionPane.showMessageDialog(null, "Error: Imposible aumentar stock");
					
					
				
			
				
				
			}
		});
		btnReducirProducto.setBackground(new Color(60, 179, 113));
		btnReducirProducto.setForeground(new Color(255, 250, 250));
		btnReducirProducto.setFont(new Font("Arial", Font.BOLD, 14));
		menuBar.add(btnReducirProducto);
		
		JButton btnReducirStock = new JButton("Reducir Stock");
		btnReducirStock.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

				String id=(String)table_1.getValueAt(table_1.getSelectedRow(), 0);
				String cantstock=(String)Menu.table_1.getValueAt(Menu.table_1.getSelectedRow(), 3);
				int stck=Integer.valueOf(cantstock.trim()).intValue();
				Object CantidadReducida=spinner.getValue();
				int cantspin=((Integer)CantidadReducida).intValue();
				if (cantspin>0){
					
				int cantactual=stck-cantspin;
				if(cantactual>=0){
					Menu.table_1.setValueAt(cantactual,Menu.table_1.getSelectedRow(),3);
				
					Menu.Super.reducirStockProducto(id,cantactual);
				}
				else{
					JOptionPane.showMessageDialog(null, "Error: La cantidad que desea reducir es mayor al stock disponible ");
				}

				
				}
				else{
					JOptionPane.showMessageDialog(null, "Error: Imposible reducir stock");
					
					
				}
			}
		});
		btnReducirStock.setForeground(new Color(255, 250, 250));
		btnReducirStock.setFont(new Font("Arial", Font.BOLD, 14));
		btnReducirStock.setBackground(new Color(60, 179, 113));
		menuBar.add(btnReducirStock);
		
		menuBar.add(spinner);
		
	
		contentPane = new JPanel();
		contentPane.setBackground(Color.WHITE);
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		
		

		
		
		JPanel panel = new JPanel();
		
		JDesktopPane desktopPane = new JDesktopPane();

		
		lblNewLabel.setBackground(Color.WHITE);
		lblNewLabel.setVerticalAlignment(SwingConstants.TOP);
		lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
		lblNewLabel.setForeground(Color.WHITE);
		lblNewLabel.setIcon(new ImageIcon("C:\\Users\\MA77DELL\\workspace\\Geant\\src\\geantlogo.png"));

		
		
		table = new JTable();
		table.setFillsViewportHeight(true);
		table.setColumnSelectionAllowed(true);
		table.setCellSelectionEnabled(true);
		table.setBackground(new Color(192, 192, 192));
		String[]Columns={"","","",""};
		String[][]rows = {{"","","",""}};
		
		table_1=new JTable(rows,Columns){

			
			private static final long serialVersionUID = 1L;
			

			public boolean isCellEditable(int rows,int Columns){
				return false;
			
			}
		};
		table_1.setForeground(Color.WHITE);
		table_1.setFont(new Font("Arial Black", Font.BOLD, 12));
		table_1.setBackground(new Color(0, 128, 128));
		table_1.setPreferredScrollableViewportSize(new Dimension(450,63));
		table_1.setFillsViewportHeight(true);
		
		JScrollPane jps= new JScrollPane(table_1);
		final JTextField bsc=new JTextField("Ingrese codigo de barras");
		bsc.setBounds(10,275,300,20);
	
	    modelo.addColumn("ID");
	    modelo.addColumn("Nombre");
	    modelo.addColumn("Precio");
	    modelo.addColumn("Cantidad");
	    table_1.setModel(modelo);
	    
	    JButton btnNewButton = new JButton("Cargar de Lista");
	    btnNewButton.setBackground(new Color(102, 205, 170));
	    btnNewButton.setFont(new Font("Tahoma", Font.BOLD, 11));
	    btnNewButton.setForeground(new Color(0, 0, 0));
	    btnNewButton.addActionListener(new ActionListener() {
	    	public void actionPerformed(ActionEvent e) {	    		JFileChooser chooser = new JFileChooser();
            chooser.setCurrentDirectory(new java.io.File("."));
            chooser.setDialogTitle("Seleccione la lista de Stock del Supermercado");
            chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            FileFilter filter = new FileFilter() {
				
				@Override
				public String getDescription() {
					// TODO Auto-generated method stub
					return "Archivos .csv";
				}
				
			    public final static String csv = "csv";

			    /*
			     * Get the extension of a file.
			     */  
			    
			    public String getExtension(File f) {
			        String ext = null;
			        String s = f.getName();
			        int i = s.lastIndexOf('.');

			        if (i > 0 &&  i < s.length() - 1) {
			            ext = s.substring(i+1).toLowerCase();
			        }
			        return ext;
			    }
			    

				@Override
				public boolean accept(File f) {
					String extension = getExtension(f);
				    if (extension != null) {
				        if (extension.equals(csv)) {
				                return true;
				        } else {
				            return false;
				        }
				    }

				    return false;
				}
			};
            chooser.setFileFilter(filter);
            if (chooser.showOpenDialog(contentPane) == JFileChooser.APPROVE_OPTION) {
            	
            	
            	//Menu.modelo.setRowCount(0);
				Menu.Super.setProductosDelSupermercado(CargarMasiva.cargarProductosDeArchivo(chooser.getSelectedFile().getPath()));
				ILista listaDeArchivo = CargarMasiva.cargarProductosDeArchivo(chooser.getSelectedFile().getPath());
				
				/*
				while(!listaDeArchivo.esVacia()) {
					IElemento elem = listaDeArchivo.quitarPrimero();
					IProducto prod = (IProducto) elem.getDatos();
					String[] rowData = {(String) prod.getCodigoBarra(),prod.getNombre(),prod.getPrecio().toString(),prod.getStock().toString()};
					Menu.modelo.addRow(rowData);
				}
				*/
				
			RefrescarTabla(listaDeArchivo);
            	
            } else {
                System.out.println("No Selection ");
            }

    		//CargarMasiva.fusionarSupermercados(Menu.Super, superDestino)
    	}
    });

	    		
	   
	    
	    JButton btnSalvarDatos = new JButton("Salvar Datos");
	    btnSalvarDatos.addActionListener(new ActionListener() {
	    	public void actionPerformed(ActionEvent e) {	    		JFileChooser chooser = new JFileChooser();
            chooser.setCurrentDirectory(new java.io.File("."));
            chooser.setDialogTitle("Seleccione la lista de Stock del Supermercado");
            chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            FileFilter filter = new FileFilter() {
				
				@Override
				public String getDescription() {
					// TODO Auto-generated method stub
					return "Archivos .csv";
				}
				
			    public final static String csv = "csv";

			    /*
			     * Get the extension of a file.
			     */  
			    
			    public String getExtension(File f) {
			        String ext = null;
			        String s = f.getName();
			        int i = s.lastIndexOf('.');

			        if (i > 0 &&  i < s.length() - 1) {
			            ext = s.substring(i+1).toLowerCase();
			        }
			        return ext;
			    }
			    

				@Override
				public boolean accept(File f) {
					String extension = getExtension(f);
				    if (extension != null) {
				        if (extension.equals(csv)) {
				                return true;
				        } else {
				            return false;
				        }
				    }

				    return false;
				}
			};
            chooser.setFileFilter(filter);
            if (chooser.showOpenDialog(contentPane) == JFileChooser.APPROVE_OPTION) {

	    		CargarMasiva.grabarProductosEnArchivo(chooser.getSelectedFile().getPath(),Menu.Super.imprimirProductos());
            	
            } else {
                System.out.println("No Selection ");
            }

    		//CargarMasiva.fusionarSupermercados(Menu.Super, superDestino)
    	}
    });
	    btnSalvarDatos.setBackground(new Color(102, 205, 170));
	    btnSalvarDatos.setFont(new Font("Tahoma", Font.BOLD, 11));
	    btnSalvarDatos.setForeground(new Color(0, 0, 0));
	    
	    JButton btnIntercalarLista = new JButton("Intercalar Lista");
	    btnIntercalarLista.addActionListener(new ActionListener() {
	     	public void actionPerformed(ActionEvent e) {	    		JFileChooser chooser = new JFileChooser();
            chooser.setCurrentDirectory(new java.io.File("."));
            chooser.setDialogTitle("Seleccione la lista de Stock del Supermercado");
            chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            FileFilter filter = new FileFilter() {
				
				@Override
				public String getDescription() {
					// TODO Auto-generated method stub
					return "Archivos .csv";
				}
				
			    public final static String csv = "csv";

			    /*
			     * Get the extension of a file.
			     */  
			    
			    public String getExtension(File f) {
			        String ext = null;
			        String s = f.getName();
			        int i = s.lastIndexOf('.');

			        if (i > 0 &&  i < s.length() - 1) {
			            ext = s.substring(i+1).toLowerCase();
			        }
			        return ext;
			    }
			    

				@Override
				public boolean accept(File f) {
					String extension = getExtension(f);
				    if (extension != null) {
				        if (extension.equals(csv)) {
				                return true;
				        } else {
				            return false;
				        }
				    }

				    return false;
				}
			};
            chooser.setFileFilter(filter);
            if (chooser.showOpenDialog(contentPane) == JFileChooser.APPROVE_OPTION) {

            	ISupermercado superAIntercalar = new TSupermercado();
            	ILista lista = CargarMasiva.cargarProductosDeArchivo(chooser.getSelectedFile().getPath());
            	superAIntercalar.setProductosDelSupermercado(lista);
            	CargarMasiva.fusionarSupermercados(superAIntercalar,Menu.Super);
            	
            } else {
                System.out.println("No Selection ");
            }

    		//CargarMasiva.fusionarSupermercados(Menu.Super, superDestino)
    	}
    });
	    btnIntercalarLista.setBackground(new Color(102, 205, 170));
	    btnIntercalarLista.setFont(new Font("Tahoma", Font.BOLD, 11));
	    btnIntercalarLista.setForeground(new Color(0, 0, 0));
	    
	    JButton btnComprar = new JButton("Agregar al carrito");
	    btnComprar.addActionListener(new ActionListener() {
	    	public void actionPerformed(ActionEvent e) {
	    		    		
	    		String id=(String)table_1.getValueAt(table_1.getSelectedRow(), 0);		
				int  cantstock=Integer.valueOf(table_1.getValueAt(table_1.getSelectedRow(),3).toString().trim()).intValue();
				IProducto prod = new TProducto(id, null, null, cantstock);
				IElemento elem = new TElemento(id, prod);
				listaADevolver.insertarAlPrincipio(elem);

				JOptionPane.showMessageDialog(null,"Producto: "+table_1.getValueAt(table_1.getSelectedRow(),1)+" agregado al carrito");
				
				
				
	    		
	    	}
	    });
	    btnComprar.setBackground(new Color(0, 255, 255));
	    btnComprar.setFont(new Font("Tahoma", Font.BOLD, 11));
	    btnComprar.setForeground(new Color(255, 255, 255));
	    
	    JButton button = new JButton("Buscar");
	    button.addActionListener(new ActionListener() {
	    	public void actionPerformed(ActionEvent arg0) {

				ILista productosDelSupermercado = new TLista();
				productosDelSupermercado=Menu.Super.getProductosDelSupermercado();

				if((productosDelSupermercado.buscar(bsc.getText()))!=null){
					Menu.Super.imprimirProducto(productosDelSupermercado.buscar(bsc.getText()).getEtiqueta());
					
					JOptionPane.showMessageDialog(null,Menu.Super.imprimirProducto(productosDelSupermercado.buscar(bsc.getText()).getEtiqueta()));
					
				}
				else{
					JOptionPane.showMessageDialog(null, "Producto no encontrado");
					
				}
	    	}
	    });
	    
	    JButton btnComprar_1 = new JButton("Comprar");
	    btnComprar_1.addActionListener(new ActionListener() {
	    	public void actionPerformed(ActionEvent arg0) {
	    		CargarMasiva.carrito(Menu.Super, listaADevolver);
	    		listaADevolver.vaciar();
	    	}
	    });
	    btnComprar_1.setForeground(Color.WHITE);
	    btnComprar_1.setFont(new Font("Tahoma", Font.BOLD, 11));
	    btnComprar_1.setBackground(Color.BLUE);
	    
	    JButton btnOrdenar = new JButton("Ordenar");
	    btnOrdenar.addActionListener(new ActionListener() {
	    	public void actionPerformed(ActionEvent arg0) {
	    		
	    		
	    		ILista listaDeArchivo=Menu.Super.listarProductoOrdenadoPorNombre();
	    		
	    		if(!listaDeArchivo.obtenerPrimero().equals(null)){
	    		Menu.modelo.setRowCount(0);
	    		
	    		while(!listaDeArchivo.esVacia()) {
					IElemento elem = listaDeArchivo.quitarPrimero();
					IProducto prod = (IProducto) elem.getDatos();
					String[] rowData = {(String) prod.getCodigoBarra(),prod.getNombre(),prod.getPrecio().toString(),prod.getStock().toString()};
					Menu.modelo.addRow(rowData);
				}
	    		//Menu.Super.setProductosDelSupermercado(listaDeArchivo);
	    		}
	    		else{
	    			JOptionPane.showMessageDialog(null, "Lista Ordenada");
	    			
	    		}
	    		
	    	}
	    });
	    btnOrdenar.setForeground(Color.WHITE);
	    btnOrdenar.setFont(new Font("Tahoma", Font.BOLD, 11));
	    btnOrdenar.setBackground(new Color(255, 0, 0));
	    GroupLayout gl_contentPane = new GroupLayout(contentPane);
	    gl_contentPane.setHorizontalGroup(
	    	gl_contentPane.createParallelGroup(Alignment.LEADING)
	    		.addGroup(gl_contentPane.createSequentialGroup()
	    			.addGap(66)
	    			.addComponent(panel, GroupLayout.PREFERRED_SIZE, 757, GroupLayout.PREFERRED_SIZE)
	    			.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
	    		.addGroup(gl_contentPane.createSequentialGroup()
	    			.addGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING)
	    				.addGroup(gl_contentPane.createSequentialGroup()
	    					.addContainerGap()
	    					.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
	    						.addComponent(btnIntercalarLista, GroupLayout.DEFAULT_SIZE, 124, Short.MAX_VALUE)
	    						.addComponent(btnNewButton, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 124, Short.MAX_VALUE)
	    						.addComponent(btnSalvarDatos, Alignment.TRAILING, GroupLayout.PREFERRED_SIZE, 124, GroupLayout.PREFERRED_SIZE))
	    					.addGap(18)
	    					.addComponent(lblNewLabel, GroupLayout.PREFERRED_SIZE, 605, GroupLayout.PREFERRED_SIZE))
	    				.addGroup(gl_contentPane.createSequentialGroup()
	    					.addComponent(desktopPane, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
	    					.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
	    						.addComponent(jps, GroupLayout.PREFERRED_SIZE, 756, GroupLayout.PREFERRED_SIZE)
	    						.addGroup(gl_contentPane.createSequentialGroup()
	    							.addComponent(bsc, GroupLayout.PREFERRED_SIZE, 220, GroupLayout.PREFERRED_SIZE)
	    							.addPreferredGap(ComponentPlacement.RELATED)
	    							.addComponent(button, GroupLayout.PREFERRED_SIZE, 85, GroupLayout.PREFERRED_SIZE)
	    							.addGap(51)
	    							.addComponent(btnOrdenar, GroupLayout.PREFERRED_SIZE, 108, GroupLayout.PREFERRED_SIZE)
	    							.addPreferredGap(ComponentPlacement.RELATED, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
	    							.addComponent(btnComprar, GroupLayout.PREFERRED_SIZE, 149, GroupLayout.PREFERRED_SIZE)
	    							.addPreferredGap(ComponentPlacement.RELATED)
	    							.addComponent(btnComprar_1, GroupLayout.PREFERRED_SIZE, 124, GroupLayout.PREFERRED_SIZE)
	    							.addGap(4)))))
	    			.addGap(93))
	    );
	    gl_contentPane.setVerticalGroup(
	    	gl_contentPane.createParallelGroup(Alignment.TRAILING)
	    		.addGroup(gl_contentPane.createSequentialGroup()
	    			.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
	    				.addGroup(gl_contentPane.createSequentialGroup()
	    					.addGap(79)
	    					.addComponent(btnNewButton)
	    					.addGap(37)
	    					.addComponent(btnSalvarDatos)
	    					.addGap(33)
	    					.addComponent(btnIntercalarLista))
	    				.addGroup(gl_contentPane.createSequentialGroup()
	    					.addContainerGap()
	    					.addComponent(lblNewLabel, GroupLayout.PREFERRED_SIZE, 230, GroupLayout.PREFERRED_SIZE)))
	    			.addGap(57)
	    			.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
	    				.addComponent(bsc, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
	    				.addComponent(btnComprar, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
	    				.addComponent(button, GroupLayout.PREFERRED_SIZE, 19, GroupLayout.PREFERRED_SIZE)
	    				.addComponent(btnOrdenar)
	    				.addComponent(btnComprar_1, GroupLayout.DEFAULT_SIZE, 23, Short.MAX_VALUE))
	    			.addPreferredGap(ComponentPlacement.UNRELATED)
	    			.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
	    				.addComponent(desktopPane, GroupLayout.PREFERRED_SIZE, 266, GroupLayout.PREFERRED_SIZE)
	    				.addComponent(jps, GroupLayout.PREFERRED_SIZE, 266, GroupLayout.PREFERRED_SIZE))
	    			.addGap(36)
	    			.addComponent(panel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
	    			.addGap(33))
	    );
	    contentPane.setLayout(gl_contentPane);
	    
	 

	   
	}
	public void RefrescarTabla(ILista lista){
		Menu.modelo.setRowCount(0);
		while(!lista.esVacia()) {
			IElemento elem = lista.quitarPrimero();
			IProducto prod = (IProducto) elem.getDatos();
			String[] rowData = {(String) prod.getCodigoBarra(),prod.getNombre(),prod.getPrecio().toString(),prod.getStock().toString()};
			Menu.modelo.addRow(rowData);
		}
		
	}
	}

	


